package cn.bdqn.filter;

import cn.bdqn.entity.AuthorityUser;
import cn.bdqn.entity.Payload;
import cn.bdqn.util.JwtUtil;
import cn.bdqn.util.RsaKeyProperties;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @ProjectName: springSecuritySeparate
 * @Package: cn.bdqn.filter
 * @Author: huat
 * @Date: 2019/12/24 18:03
 * @Version: 1.0
 */
public class JwtVerifyFileter extends BasicAuthenticationFilter {
    private RsaKeyProperties rsaKeyProperties;

    public JwtVerifyFileter(AuthenticationManager authenticationManager, RsaKeyProperties rsaKeyProperties) {
        super(authenticationManager);
        this.rsaKeyProperties = rsaKeyProperties;
    }

    @Override
    public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        // request.getHeader("Authorization")这个括号中的值需要和
        // JwtTokenFilter这个类中successfulAuthentication方法中
        //  response.setHeader("Authorization","bearer "+token);的括号中的第一个值一致
        String header = request.getHeader("Authorization");
        // header.startsWith("bearer ")这个括号中的值需要和
        // JwtTokenFilter这个类中successfulAuthentication方法中
        // response.setHeader("Authorization","bearer "+token);的括号中的第二个值加号前一致
        if (header == null || !header.startsWith("bearer ")) {
            //如果没有登陆提示用户进行登陆
            response.setContentType("application/json;charset=utf-8");
            //返回403状态码
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            //响应流
            PrintWriter out = response.getWriter();
            //封装返回数据
            Map<String, Object> resultMap = new HashMap<String, Object>();
            resultMap.put("code", HttpServletResponse.SC_FORBIDDEN);
            resultMap.put("data", "");
            resultMap.put("msg", "请登录");
            //new ObjectMapper().writeValueAsString(resultMap)将map转成json
            out.write(new ObjectMapper().writeValueAsString(resultMap));
            out.flush();
            out.close();

            chain.doFilter(request, response);
        } else {
            //获取token
            String token=header.replace("bearer ","");
            //验证token是否正确
            Payload<AuthorityUser> payload= JwtUtil.getInfoFromToken(token,rsaKeyProperties.getPublicKey(), AuthorityUser.class);
            AuthorityUser user=payload.getUserInfo();
           if(null!=user){
               UsernamePasswordAuthenticationToken authResult=new UsernamePasswordAuthenticationToken(user.getUsername(),null,user.getAuthorities());
               SecurityContextHolder.getContext().setAuthentication(authResult);
               chain.doFilter(request, response);
           }
        }
    }
}
